package manager

import android.os.Environment
import ext.log
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.concurrent.TimeUnit

object NetworkManager {

    private val ADV_URL  // 获取广告
        get() = "${AppManager.baseUrl}/adviertisement/giveAdviertiseToClient.json"

    /**
     * 获取库存 根据小时计算过期时间
     */
    private val WARES_NEW_URL
        get() = "${AppManager.baseUrl}/goodssearch/hours/goods-info/list.json"

    private val STATUS_DLY_URL  // 上传状态
        get() = "${AppManager.baseUrl}/status/receiveGemini.json"

    private val STATUS_3_URL  // 3分钟一次上传状态
        get() = "${AppManager.baseUrl}/status/receiveGeminiTemperature.json"

    private val REPORT_URL  // 扣减库存
        get() = "${AppManager.baseUrl}/replenishment/deduction/sell.json"

    private val HEAT_URL  // 温度控制
        get() = "${AppManager.baseUrl}/worn/giveTemp.json"

    private val TEMP_URL  // 温度报警
        get() = "${AppManager.baseUrl}/worn/give.json"

    private val CHECK_URL  // 校验用户
        get() = "${AppManager.baseUrl}/checkMain/main-info/check.json"

    /**
     * 根据条码获取库存
     */
    private val REPLENISH_BAR_CODE_URL
        get() = "${AppManager.baseUrl}/replenishment/scancode/verification.json"

    private val SELL_STATUS_URL  // 获取停售or在售状态
        get() = "${AppManager.baseUrl}/sbzt/giveStatus.json"

    private val LOG_URL
        get() = "${AppManager.baseUrl}/mach/client/logging"

    private const val DEBUG_URL = "http://ut.hontech-rdcenter.com:33445/log/create"

    private val mHttpClient = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(120, TimeUnit.SECONDS)
        .build()

    private val mMediaType = MediaType.parse("application/json; charset=utf-8")

    private fun post(url: String, content: String): String {
        val body = RequestBody.create(mMediaType, content)
        val request = Request.Builder().url(url).post(body).build()
        val call = mHttpClient.newCall(request)
        val response = call.execute()
        return response.body()?.string() ?: throw IOException("network error")
    }

    fun postLog(msg: String) {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        json.put("status", msg)
        post(LOG_URL, json.toString())
    }

    fun postProgInfo(prog: Int, value: Int) {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        json.put("order", AppManager.MachCode)
        json.put("prog", prog)
        json.put("value", value)
        val s = json.toString()
        post(DEBUG_URL, s)
    }

    /**
     * 即使状态更新
     */
    fun updateDlyStatusToServer(content: String): String {
        return post(STATUS_DLY_URL, content)
    }

    /**
     * 3分钟上次一次数据
     */
    fun update3StatusToServer(content: String): String {
        return post(STATUS_3_URL, content)
    }

    /**
     * 更新加热数据
     */
    fun refreshControlHeatData(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        val content = json.toString()
        return post(HEAT_URL, content)
    }

    /**
     * 更新报警温度数据
     */
    fun refreshTempValue(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        val content = json.toString()
        return post(TEMP_URL, content)
    }

    /**
     * 更新商品信息
     */
    fun refreshWaresWithServer(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        val content = json.toString()
        log(content, "获取商品-请求")
        return post(WARES_NEW_URL, content)
    }

    /**
     * 更新广告信息
     */
    fun refreshAdvWithServer(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        val content = json.toString()
        log(content, "获取广告-请求")
        return post(ADV_URL, content)
    }

    /**
     * 登陆
     */
    fun checkIdAndPassword(id: String, password: String): Boolean {
        val jsonObject = JSONObject()
        jsonObject.put("emplCode", id)
        jsonObject.put("password", password)
        jsonObject.put("macAddr", AppManager.MacAddress)

        val result = post(CHECK_URL, jsonObject.toString())
        log("登陆返回:$result")
        val json = JSONObject(result)
        val ret = json.optBoolean("success")
        return ret
    }

    fun downLoadFile(name: String, url: String): File {
        log("开始下载:$name")
        val request = Request.Builder().get().url(url).build()
        val call = mHttpClient.newCall(request)
        val response = call.execute()
        val bytes = response.body()!!.bytes()
        log("下载的数据大小:${bytes.size}")
        val file = File(Environment.getExternalStorageDirectory(), name)
        if (file.exists()) {
            file.delete()
        }
        val ret = file.createNewFile()
        log("创建文件:$ret")
        val out = FileOutputStream(file, false)
        out.write(bytes)
        out.flush()
        out.close()
        return file
    }

    fun downData(url: String): ByteArray {
        val request = Request.Builder().get().url(url).build()
        val call = mHttpClient.newCall(request)
        val response = call.execute()
        val bytes = response.body()!!.bytes()
        log("下载的数据大小:${bytes.size}")
        return bytes
    }

    /**
     * 扣减库存
     */
    fun reportWithServer(content: String): String {
        return post(REPORT_URL, content)
    }

    /**
     * 更新是否停售
     */
    fun refreshSellWithServer(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        return post(SELL_STATUS_URL, json.toString())
    }

    /**
     * 根据条码进行补货
     */
    fun replenishBybarCode(content: String): String {
        return post(REPLENISH_BAR_CODE_URL, content)
    }

}